package com.itheima.exception;

import com.itheima.pojo.Result;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理唯一键冲突异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        // 1. 获取根因异常
        Throwable rootCause = NestedExceptionUtils.getRootCause(e);

        // 2. 处理MySQL唯一键冲突
        if (rootCause instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException sqlEx = (SQLIntegrityConstraintViolationException) rootCause;
            String errorMessage = sqlEx.getMessage();

            // 3. 识别具体冲突类型
            if (errorMessage != null) {
                if (errorMessage.contains("emp.phone")) {
                    return Result.error("手机号已被注册，请更换其他手机号");
                }
                if (errorMessage.contains("emp.username")) {
                    return Result.error("用户名已存在，请选择其他用户名");
                }
                if (errorMessage.contains("Duplicate entry")) {
                    return Result.error( "数据已存在，请勿重复提交");
                }
            }
        }

        // 4. 默认错误响应
        return Result.error("数据提交失败，请稍后重试");
    }

    /**
     * 处理班级下有学生的异常
     */
    @ExceptionHandler(ClassHasStudentsException.class)
    public Result handleClassHasStudents(ClassHasStudentsException ex) {
        ex.printStackTrace();//打印堆栈中的异常信息
        return Result.error(ex.getMessage());
    }
    //全局异常处理异常
    @ExceptionHandler(Exception.class)
    public Result ex(Exception e){//方法形参中指定能够处理的异常类型
        e.printStackTrace();//打印堆栈中的异常信息
        //捕获到异常之后，响应一个标准的Result
        return Result.error("对不起,操作失败,请联系管理员");
    }

}